// Copyright 2009 Pigasus.
// GNU GPL v2.
// Author: John Zhang and Jordan Rupprecht.

#include "wait.h"

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

#include "common.h"
#include "threadpool.h"

using namespace std;

extern ThreadPool *job_thread_pool;
extern pthread_mutex_t *mutex_job_thread_pool;

void Wait(int job_id) {
  while (true) {
    pthread_mutex_lock(mutex_job_thread_pool);
    int status = job_thread_pool->GetStatus(job_id);
    pthread_mutex_unlock(mutex_job_thread_pool);

    if (status == kThreadStatusUndefined) {
      // TODO: Decide what to do if the user specifies a job thread ID which is
      // invalid. For now, it will exit.
      debug("Job thread ID %d is undefined.\n", job_id);
      break;
    } else if (status == kThreadStatusDone) {
      break;
    }

    sleep(kDefaultWaitDelay);
  }
}

void WaitAll() {
  while (true) {
    pthread_mutex_lock(mutex_job_thread_pool);
    bool has_jobs_running = job_thread_pool->HasJobsRunning();
    pthread_mutex_unlock(mutex_job_thread_pool);

    if (has_jobs_running) {
      sleep(kDefaultWaitDelay);
    } else {
      break;
    }
  }
}
